# -*- coding: utf-8 -*-
from datetime import date, datetime
from dao.db import db
from werkzeug.security import check_password_hash

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.BigInteger, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    name = db.Column(db.String(50), nullable=False)
    role = db.Column(db.Enum('admin', 'teacher', 'student'), nullable=False)
    
    # 关系
    student_info = db.relationship('Student', backref='user', uselist=False)
    teacher_info = db.relationship('Teacher', backref='user', uselist=False)

class Student(db.Model):
    __tablename__ = 'students'
    id = db.Column(db.BigInteger, primary_key=True)
    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), unique=True, nullable=False)
    student_id = db.Column(db.String(20), unique=True, nullable=False)
    class_id = db.Column(db.BigInteger, db.ForeignKey('classes.id'), nullable=False)
    school_position = db.Column(db.String(50))
    class_position = db.Column(db.String(50))
    performance_points = db.Column(db.Integer, default=0)
    group_id = db.Column(db.BigInteger)

class Teacher(db.Model):
    __tablename__ = 'teachers'
    id = db.Column(db.BigInteger, primary_key=True)
    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), unique=True, nullable=False)
    position = db.Column(db.String(127))
    class_id = db.Column(db.BigInteger, db.ForeignKey('classes.id'))
    password_hash = db.Column(db.String(255), nullable=False)

class Class(db.Model):
    __tablename__ = 'classes'
    id = db.Column(db.BigInteger, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    grade = db.Column(db.Integer, nullable=False)
    head_teacher_id = db.Column(db.BigInteger, db.ForeignKey('teachers.id'))

def get_user_by_username(username):
    """通过用户名获取用户信息"""
    return User.query.filter_by(username=username).first()

def verify_password(user, password):
    """验证密码"""
    # 注意：实际项目中密码应该使用哈希存储
    # 这里假设数据库中存储的是明文密码，仅用于演示
    return user.password == password
    # 生产环境中应该使用：
    # return check_password_hash(user.password, password)

class TeacherStudentManagement(db.Model):
    __tablename__ = 'teacher_student_management'

    id = db.Column(db.BigInteger, primary_key=True)
    teacher_id = db.Column(db.BigInteger, nullable=False)
    student_id = db.Column(db.BigInteger, nullable=False)
    start_date = db.Column(db.Date, nullable=False, default=date.today)
    end_date = db.Column(db.Date, nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)

    __table_args__ = (
        db.UniqueConstraint('teacher_id', 'student_id', 'start_date', name='uk_teacher_student_date'),
        {'comment': '教师管辖学生关系表'}
    )